package com.example.config.httpclient;


import com.example.pojo.config.WeChatConfig;
import com.example.pojo.http.resp.WeChatAccessTokenResp;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * 微信 获取 AccessToken 的 http 请求
 */
@Component
public class WeChatAccessClient {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private WeChatConfig config;

    /**
     * 构建如下请求
     * https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
     *
     * @param code
     * @param state
     * @return
     */
    public WeChatAccessTokenResp getAccessToken(String code, String state) {
        //构建 restTemplate.exchange 所需参数
        String url = new StringBuilder()
                .append(config.getTokenUrl())
                .append("?").append("appid=").append(config.getAppId())
                .append("&").append("secret=").append(config.getAppSecret())
                .append("&").append("code=").append(code)
                .append("&").append("grant_type=").append("authorization_code")
                .toString();

        WeChatAccessTokenResp accessTokenResp = restTemplate.getForObject(url, WeChatAccessTokenResp.class);
        return accessTokenResp;
    }
}
